(function($, com) {
	var state = app.getState();
	var uid = state.user_id;
	var getObjLen = function(obj) {
		return Object.keys(obj).length;
	}
	
	$('#chat-area').on('longtap', 'li', msgIndexTap);
	$('#chat-area').on('tap', 'li', openchatWin);


	/**
	 * 获取单个聊天对象
	 */
	com.getChat = function(roomId) {
		var data = plus.storage.getItem(uid + 'persondata' + roomId);
		//var data = localStorage.getItem(uid + 'persondata' + roomId);
		//console.log(data);
		if(data) {
			return JSON.parse(data);
		} else {
			return {};
		}
	};
	/**
	 * 设置单个聊天对象数据
	 * @param {Object} data
	 */
	com.setChat = function(roomId, data) {
		plus.storage.setItem(uid + 'persondata' + roomId, JSON.stringify(data));
		//console.log(JSON.stringify(data));
		//localStorage.setItem(uid + 'persondata' + roomId, JSON.stringify(data));
	}
	com.removeChat = function(roomId) {
		plus.storage.removeItem(uid + 'persondata' + roomId);
		//localStorage.removeItem(uid + 'persondata' + roomId);
	}
	var sorttime = function(a, b) {
		return b['add_time'] - a['add_time'];
	};
	/**
	 * 设置首页缓存
	 * @param {Object} data
	 */
	com.setIndex = function(data) {
		//console.log(JSON.stringify(data));
		var rt = {};
		for(var p in data) {
			if(data[p]) {
				rt[p] = data[p];
			}
		}
		localStorage.setItem(uid + 'indexdata', JSON.stringify(rt));
	};
	/**
	 * 获取首页缓存
	 */
	com.getIndex = function() {
		//localStorage.clear();
		//plus.storage.clear();
		var data = localStorage.getItem(uid + 'indexdata');
		//console.log(data);
		if(data) {
			return JSON.parse(data);
		} else {
			return {};
		}
	};
	com.HTMLDecode = function(text) {
		var temp = document.createElement("div");
		temp.innerHTML = text;
		var output = temp.innerText || temp.textContent;
		temp = null;
		return output;
	}

	com.getList = function() {
		var data = com.getIndex();

		var len = getObjLen(data);

		var top = [];
		var main = [];
		if(len < 1) {
			return main;
		}

		for(var p in data) {
			var show = data[p];
			if(!show) {
				continue;
			}
			

			if(show['ctype'] == 2) {

				show['avatar'] = 'static/images/qun.png';

			} else {
				//show['avatar'] = serverurl + 'upload/avatar/' + p + '.jpg';
				show['avatar'] = dispimg + 'avatar/' + p + '.jpg';
				
				
				if(!CheckImgExists(show['avatar'])){
					show['avatar'] = 'static/images/1.png';
				}


			}

			//show['msgnum'] = data[p]['msgnum'];
			//show['istop'] = data[p]['istop'] || 0;
			//show['msg'] = app.parseMainMsg(show['t_msg'], show['r_type']);
			show['show_time'] = app.dateStr(show['add_time']);
			show['key'] = p;
			if(p == 1) {
				show['avatar'] = 'static/images/kefu3.png';
			}
			if(p == 2) {
				show['avatar'] = 'static/images/kefu1.png';
			}
			if(show['name']) {
				if(show['istop'] > 0) {
					top.push(show);
				} else {
					main.push(show);
				}
			}

		}
		//app.arrSort(main, 'add_time');
		top.sort(sorttime);
		main.sort(sorttime);
		top.push.apply(top, main);
		return top;
	}
	var sortmsg = function(a, b) {
		return a['add_time'] - b['add_time'];
	};
	/**
	 * 获取单个聊天对象
	 */
	com.get = function(roomId) {
		var data = com.getChat(roomId);
		var cache = [],
			list = data['list'];
//		var lastId = 0;
		for(var p in list) {
			cache.push(list[p]);
		}
		cache.sort(sortmsg);
		/*
		for(var i = 0; i < cache.length; i++) {
			if(cache[i]['m_id']) {
				lastId = cache[i]['m_id'];
			}
		}
		data['lastId'] = lastId;*/
		data['list'] = cache;

		return data;
	}
	/**
	 * 设置单个聊天对象
	 */
	com.set = function(roomId, msgInfo) {
		var data = com.getIndex();
		var chat = com.getChat(roomId);
		var id = msgInfo['id'] || com.getId(roomId);
		if(typeof data[roomId] !== 'object' || !data[roomId]) {
			data[roomId] = {};
		}
		if(typeof chat['list'] !== 'object' || !chat['list']) {
			chat['list'] = {};
		}
		if(msgInfo['f_id'] !== uid) {
			// modify by yaozy 修改进入聊天页后未读消息会变成10的问题
			if (msgInfo.isread !== '1') {
				data[roomId]['msgnum'] = (data[roomId]['msgnum'] | 0) + 1;
			}
			
			//data[roomId]['msgnum'] = data[roomId]['msgnum'] + 1;
			data[roomId]['name'] = msgInfo['f_name'];
			chat['name'] = msgInfo['f_name'];
		} else {
			data[roomId]['msgnum'] = 0;
			data[roomId]['name'] = msgInfo['t_name'];
			chat['name'] = msgInfo['t_name'];
		}
		if(msgInfo['ctype'] == 1) {
			//data[roomId]['name'] = msgInfo['t_name'];
			//chat['name'] = msgInfo['t_name'];
			data[roomId]['avatar'] = app.avatar(roomId, 'static/images/1.png');
			chat['avatar'] = app.avatar(roomId, '../../static/images/1.png');
			if(msgInfo['f_id'] !== uid) {
				var friend = com.getFriendData(roomId);
				if(friend['userdesc']) {
					data[roomId]['name'] = friend['userdesc'];
					chat['name'] = friend['userdesc'];
				}
			}

		} else {
			//data[roomId]['msgnum']++;
			data[roomId]['name'] = msgInfo['t_name'];
			data[roomId]['avatar'] = app.avatar(roomId, 'static/images/qun.png');
			chat['name'] = msgInfo['t_name'];
			chat['avatar'] = app.avatar(roomId, 'static/images/qun.png');
		}
		data[roomId]['ctype'] = msgInfo['ctype'];
		data[roomId]['r_type'] = msgInfo['r_type'];
		chat['key'] = roomId;
		chat['list'][id] = msgInfo;
		data[roomId] = com.parseIndexData(data[roomId], msgInfo, roomId);
		//console.log(JSON.stringify(chat));
		//console.log(JSON.stringify(data));
//		if(msgInfo['lastId']) {
//			data['lastId'] = msgInfo['lastId'];
//		}
		if (msgInfo.m_id) {
			data[roomId].lastId = msgInfo.m_id;
		}
		com.setChat(roomId, chat);
		com.setIndex(data);
	}
	com.getFriendData = function(fid) {
		var mydata = localStorage.getItem('contactlist' + uid);
		if(!mydata || !app.isJson(mydata)) {
			return [];
		}
		var data = JSON.parse(mydata);
		var rt = {};
		for(var p in data) {
			if(data[p]['f_id'] == fid) {
				rt = data[p];
				break;
			}
		}
		return rt;
	};
	com.parseIndexData = function(data, msg, roomId) {
		data['t_msg'] = msg['t_msg'];

		data['msg'] = com.HTMLDecode(data['t_msg']);
		data['msg'] = app.parseMainMsg(data['msg'], msg['r_type']);
		data['msg'] = (data['msg'] == "undefined") ? '[消息]' : data['msg'];
		//data['msg'] = data['msg'].replace(/<img(?:.|\s)*?>/g,'');
		data['add_time'] = msg['add_time'];
		data['istop'] = data['istop'] ? data['istop'] : 0;
		data['id'] = msg['id'];
		data['key'] = roomId;
		if(msg['ctype']) {
			data['ctype'] = msg['ctype'];
		}

		return data;
	}
	
	com.lastId = function (roomId) {
		var data = com.getIndex()[roomId];
		return data && data.lastId || 0;
	}
	
	com.clearnum = function(roomId) {
		var data = com.getIndex();
		if(data[roomId]) {
			data[roomId]['msgnum'] = 0;
		}

		com.setIndex(data);
	}
	com.getOne = function(roomId, id) {
		var data = com.getChat(roomId);
		return data['list'][id];
	}
	com.edit = function(roomId, id, field, val) {
		var data = com.getChat(roomId);
		data['list'][id][field] = val;
		com.setChat(roomId, data);
	}
	com.setnum = function(roomId, num) {
		var data = com.getIndex();
		data[roomId]['msgnum'] = num;
		com.setIndex(data);
	};
	com.getval = function(roomId, field) {
		var data = com.getIndex();
		return data[roomId][field];
	};
	com.setval = function(roomId, field, val) {
		var data = com.getIndex();
		data[roomId][field] = val;
		com.setIndex(data);
	};
	/**
	 * 删除单个聊天组
	 * @param {Object} roomId
	 */
	com.del = function(roomId) {
		var data = com.getIndex();
		delete data[roomId];
		com.setIndex(data);
		com.removeChat(roomId);
	}
	/**
	 * 删除单个聊天组的某句话
	 * @param {Object} roomId
	 */
	com.delOne = function(roomId, id) {
		var data = com.getChat(roomId);
		//console.log(JSON.stringify(data));
		delete data['list'][id];
		//console.log(JSON.stringify(data));
		com.setChat(roomId, data);
	}
	com.getId = function(roomId) {
		return uid + '-' + roomId + '-' + Date.parse(new Date());
	};
	com.updateList = function() {
		mui.get(apiurl + 'chat/showlist?user_id=' + uid, function(res) {
			//console.log(JSON.stringify(res));
			if(res.status > 0) {
				com.parseList(res);
			}
		});
	};
	com.parseList = function(rtinfo) {
		var person = rtinfo['person'];
		var personlen = person.length;
		var room = rtinfo['room'];
		var roomlen = room.length;
		var data = com.getIndex();
		var cache = {};
		//console.log(JSON.stringify(data));
		if(personlen > 0) {
			for(var i = 0; i < personlen; i++) {
				var pdata = person[i];
				var roomId = pdata['f_id'];
				if(!data[roomId]) {
					data[roomId] = {};
				}
				/*
				if(!cache[roomId]) {
					cache[roomId] = {};
				}*/
				data[roomId]['ctype'] = 1;
				data[roomId]['r_type'] = pdata['r_type'];
				data[roomId]['name'] = pdata['f_name'];
				data[roomId]['avatar'] = pdata['f_header'];
				//var msgnum = 0;
				var idkey = (pdata['id'] && pdata['id'] != '0') ? pdata['id'] : com.getId(roomId) + parseInt(Math.random() * 10000);
				//console.log(idkey);
				//console.log(cache[roomId]);
				pdata['id'] = idkey;
				//cache[roomId][idkey] = pdata;
				if(!data[roomId]['msgnum'] || data[roomId]['msgnum'] >= personlen) {
					data[roomId]['msgnum'] = 0;
				}
				data[roomId]['msgnum'] = data[roomId]['msgnum'] + 1;
				data[roomId] = com.parseIndexData(data[roomId], pdata, roomId);
				//console.log(JSON.stringify(data[roomId]));

			}

		}

		if(roomlen > 0) {
			for(var p = 0; p < roomlen; p++) {
				var pdata = room[p];
				var roomId = pdata['t_id'];
				if(roomId == uid) {
					continue;
				}
				if(!data[roomId]) {
					data[roomId] = {};
				}
				/*
				if(!cache[roomId]) {
					cache[roomId] = {};
				}*/
				data[roomId]['name'] = pdata['t_name'];
				data[roomId]['ctype'] = 2;
				data[roomId]['r_type'] = pdata['r_type'];
				//data[roomId]['avatar'] = 'static/images/qun.png';
				var idk = (pdata['id'] && pdata['id'] != '0') ? pdata['id'] : com.getId(roomId) + parseInt(Math.random() * 10000);
				pdata['id'] = idk;
				//cache[roomId][idk] = pdata;
				if(!data[roomId]['msgnum'] || data[roomId]['msgnum'] >= roomlen) {
					data[roomId]['msgnum'] = 0;
				}
				data[roomId]['msgnum']++;
				data[roomId] = com.parseIndexData(data[roomId], pdata, roomId);
			}
		}
		if(!data[1] && uid != 1) {
			data[1] = {
				name: 'GAT World',
				ctype: 1,
				r_type: 'text',
				msgnum: 0,
				msg: '开启未来之门',
				//avatar: 'static/images/kefu2.png',
				add_time: Date.parse(new Date()) / 1000
			};
		}

		if(!data[2] && uid != 2) {
			data[2] = {
				name: '小G',
				ctype: 1,
				r_type: 'text',
				msgnum: 0,
				msg: '我是客服！',
				//avatar: 'static/images/kefu2.png',
				add_time: Date.parse(new Date()) / 1000
			};
		}

		/*
		var rt = {};
		for(var rId in data) {

			var listdata = data[rId];
			//console.log(listdata);
			if(typeof listdata === 'object' && rId > 0) {
				rt[rId] = listdata;
			} else {
				continue;
			}
			
			var chatdata = com.getChat(rId);

			var cachedata = cache[rId];
			chatdata['name'] = listdata['name'];
			chatdata['key'] = rId;
			//chatdata['avatar'] = app.avatar(rId, '../../static/images/1.png');
			if(typeof chatdata['list'] !== 'object' || !chatdata['list']) {
				chatdata['list'] = {};
			}
			for(var id in cachedata) {
				chatdata['list'][id] = cachedata[id];
			}
			//console.log(JSON.stringify(chatdata));
			com.setChat(rId, chatdata);
		}*/

		//com.setIndex(rt);
		com.setIndex(data);
	};
	/**
	 * 自定义弹出层
	 * @param {Object} opt
	 */
	var mypopover = function(opt) {
		var el;
		if(typeof opt === 'object') {
			el = document.querySelector(opt.el);
			if(opt.style) {
				el.setAttribute('style', opt.style);
			}
		} else {
			el = document.querySelector(opt);
		}
		var mask;
		if(!mask) {
			mask = mui.createMask(function() {
				el.classList.remove('mui-active');
				return true;
			});
		}

		this.open = function() {
			mask.show();
			el.classList.add('mui-active');
		}

		this.close = function() {
			console.log('1');
			el.classList.remove('mui-active');
			document.getElementsByClassName('mui-backdrop').style.display = 'none';
			mask.close();

		}
	}
	//长按消息框
	function msgIndexTap(e) {console.log(new Date())
		//console.log('触发长按');
		var el = this,
			btns = [{
				title: "删除聊天",
				tags: 'del'
			}],
			msgnum = el.getAttribute('msgnum') || 0,
			istop = el.getAttribute('istop') * 1 || 0,
			room_id = el.getAttribute('room_id'),
			data_id = el.getAttribute('data_id'),
			ctype = el.getAttribute('room-type');
		//console.log(datatype);
		if(msgnum > 0) {
			btns.push({
				title: '标为已读'
			});
		} else {
			btns.push({
				title: '标为未读'
			});
		}
		if(istop > 0) {
			btns.push({
				title: '取消置顶'
			});
		} else {
			btns.push({
				title: '设为置顶'
			});
		}
		//var pop = new popover('#pop');
		//pop.open();

		plus.nativeUI.actionSheet({
			title: "操作",
			cancel: "取消",
			buttons: btns
		}, function(e) {
			//console.log("User pressed: " + e.index);
			var id = e.index;
			console.log(id);
			if(id > 0) {
				//删除
				if(id == 1) {
					com.del(room_id);
					el.parentNode && el.parentNode.removeChild(el);

				} else if(id == 2) {
					var badge = el.querySelector('.mui-badge');
					var setval = 0;
					if(msgnum && msgnum > 0) {
						if(badge) {
							badge.parentNode.removeChild(badge);
						}
					} else {
						setval = 1;
						if(!badge) {
							var badge = document.createElement("span");
							var targetprent = el.querySelector('.mui-table-cell');
							var targetimg = targetprent.querySelector('img.mui-media-object');
							badge.setAttribute('class', 'mui-badge');
							badge.innerHTML = 1;
							targetprent.insertBefore(badge, targetimg.nextSibling);
						} else {
							badge.innerHTML = 1;
						}
					}
					el.setAttribute('msgnum', setval);
					//com.edit(room_id, data_id, 'msgnum', setval);
					com.setval(room_id, 'msgnum', setval);
				} else if(id == 3) {
					if(istop > 0) {
						setval = 0;
					} else {
						setval = 1;
					}
					//com.edit(room_id, data_id, 'istop', setval);
					com.setval(room_id, 'istop', setval);
					com.renderlist();
				}
				//弹出菜单的显示、隐藏
				mui('.mui-popover-action').popover('toggle');
				//return true;
				//li.parentNode.removeChild(li);
			} else {
				mui('.mui-popover-action').popover('toggle');
				// return true;
			}
		});
	};

	function openchatWin() {
		var titleName = this.getAttribute('title');
		var headerImg = this.querySelector('img').getAttribute('src');
		var roomId = this.getAttribute('room_id');
		var roomType = this.getAttribute('room-type');
		
		// add by yaozy 清除当前房间的未读消息
		com.clearnum(roomId);
		
		//location.href = 'pages/chat/chat_index.html?chatTitle=' + titleName + '&chatHeader=' + headerImg + '&roomId=' + roomId + '&roomType' + roomType; 
		mui.openWindow({
			url: '/pages/chat/chat_index.html',
			id: 'chatbox',
			show: {
				autoShow: true,
				aniShow: 'slide-in-right',
				duration: 100
			},
			extras: {
				chatTitle: titleName,
				chatHeader: headerImg,
				roomId: roomId,
				roomType: roomType
			}
		});
	}
	com.renderlist = function() {
		var chatdata = com.getList();
		
		document.querySelector("#chat-area").innerHTML = template('chat-templete', {
			"mainlist": chatdata
		});
		//console.log(chatdata.length);
		document.getElementById('item1').style.height = chatdata.length * 60 + 'px';
	}
	
	com.getRoom = function(room_id) {
		var qdata = JSON.parse(localStorage.getItem('qunlist' + uid)) || [];
		var news = [],
			len = qdata.length,
			i = 0,
			has = false;
		for(; i < len; i++) {
			if(qdata[i]['room_id'] == room_id) {
				news = qdata[i];
				has = true;
				break;
			}
		}
		return news;
	};

}(mui, window.chat = {}));

function CheckImgExists(imgurl) {  
    var ImgObj = new Image(); //判断图片是否存在  
    ImgObj.src = imgurl;  
    //没有图片，则返回-1  
    if (ImgObj.fileSize > 0 || (ImgObj.width > 0 && ImgObj.height > 0)) {  
        return true;  
    } else {  
        return false;
    }  
} 